package com.mall.order.mq.delay;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author lxy
 * @create 2021-11-03 17:08
 */
@Slf4j
@Component
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    // 初始化producer
    @PostConstruct  // spring在初始化DelayOrderCancelProducer的时候就初始化这个对象(producer)
    public void init() {
        producer = new DefaultMQProducer("delay_order_cancel_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送用来实现订单超时自动取消的延迟消息
     *
     * @param orderId
     * @return
     */
    public boolean sendDelayOrderMessage(String orderId) {
        log.info("enter sendDelayOrderMessage {}", orderId);
        // 准备待发送的消息
        Message message = new Message("delay_order_cancel", orderId.getBytes(Charset.forName("utf-8")));
        // 延迟消息，需要制定消息的延迟级别
        // 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        // 1  2  3   4   5  6  7  8  9  10 11 12 13  14  15 16  17 18
        message.setDelayTimeLevel(4);
        SendResult send = null;
        try {
            log.info("before send message {}", orderId);
            send = producer.send(message);
        } catch (MQClientException e) {
            log.error("com.mall.order.mq.delay.DelayOrderCancelProducer.sendDelayOrderMessage occur exception:" + e);
            e.printStackTrace();
        } catch (RemotingException e) {
            log.error("com.mall.order.mq.delay.DelayOrderCancelProducer.sendDelayOrderMessage occur exception:" + e);
            e.printStackTrace();
        } catch (MQBrokerException e) {
            log.error("com.mall.order.mq.delay.DelayOrderCancelProducer.sendDelayOrderMessage occur exception:" + e);
            e.printStackTrace();
        } catch (InterruptedException e) {
            log.error("com.mall.order.mq.delay.DelayOrderCancelProducer.sendDelayOrderMessage occur exception:" + e);
            e.printStackTrace();
        }

        if (send != null && SendStatus.SEND_OK.equals(send.getSendStatus())) {
            // 此时消息发送成功
            return true;
        }
        // 消息发送失败
        return false;
    }
}
